<template>
    <div class="container">
      <el-card>
        <!-- 搜索和筛选 -->
        <div class="filter-container">
          <el-input v-model="search" placeholder="搜索姓名或者手机号" style="width: 400px" />
          <el-select v-model="genderFilter" placeholder="按性别筛选" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="男" value="M" />
            <el-option label="女" value="F" />
          </el-select>
          <el-button type="primary" plain @click="fetchData">搜索</el-button>
          <el-button type="info" plain @click="reset_query">重置</el-button>
          <el-button type="primary" @click="openDialog">新增学生</el-button>
        </div>
  
        <!-- 表格 -->
        <el-table :data="students" border style="width: 100%">
          <el-table-column prop="name" label="姓名" width="200" />
          <el-table-column prop="age" label="年龄" width="120"/>
          <!-- <el-table-column prop="gender" label="性别" width="120">
            <template #default="{row}">{{ row.gender === 'M' ? '男' : '女' }}</template>
          </el-table-column> -->
          <el-table-column prop="gender_display" label="性别" width="120">
            <template #default="{row}">{{ row.gender_display}}</template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="300"/>
          <el-table-column prop="phone" label="手机号" width="200"/>
          <el-table-column label="操作" width="200">
            <template #default="{row}">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          @current-change="fetchData"
          @size-change="fetchData"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50]"
        />
      </el-card>
  
      <!-- 表单对话框 -->
      <el-dialog v-model="dialogVisible" :title="formTitle">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="form.age" :min="1" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio label="M">男</el-radio>
              <el-radio label="F">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { getStudents, createStudent, updateStudent, deleteStudent } from '@/api/student'
  import type { Student, ListParams, StudentDto, PageResult } from '@/types/student'
  
  // 数据相关
  const students = ref<StudentDto[]>([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const search = ref('')
  const genderFilter = ref('')
  
  // 表单相关
  const dialogVisible = ref(false)
  const formTitle = ref('新增学生')
  const formRef = ref<FormInstance>()
  const form = reactive<Student>({
    name: '',
    age: 18,
    gender: 'M',
    email: '',
    phone: ''
  })
  
  // 验证规则
  const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ]
  }
  
  // 获取数据
  const fetchData = async () => {
    const params: ListParams = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: search.value.trim(),  // 去除前后空格
      gender: genderFilter.value === 'M' || genderFilter.value === 'F' ? genderFilter.value : undefined
    }

    // 删除空值参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    )

    const res = await getStudents(filteredParams)
    students.value = res.data.results
    total.value = res.data.count
  }

  const reset_query = async() => {
    search.value = ''
    genderFilter.value = ''
    fetchData()
  }
  
  // 打开表单对话框
  const openDialog = () => {
    formTitle.value = '新增学生'
    Object.assign(form, {
      id: undefined,
      name: '',
      age: 18,
      gender: 'M',
      email: '',
      phone: ''
    })
    dialogVisible.value = true
  }
  
  // 提交表单
  const submitForm = async () => {
    await formRef.value?.validate()
    if (form.id) {
      await updateStudent(form.id, form)
    } else {
      await createStudent(form)
    }
    dialogVisible.value = false
    fetchData()
  }
  
  // 编辑处理
  const handleEdit = (row: Student) => {
    formTitle.value = '编辑学生'
    Object.assign(form, row)
    dialogVisible.value = true
  }
  
  // 删除处理
  const handleDelete = async (id: number) => {
    await deleteStudent(id)
    fetchData()
  }
  
  onMounted(() => {
    fetchData()
  })
  </script>
  
  <style scoped>
  .container {
    display: flex;
    align-items: baseline; /* 垂直居中 */
    min-height: 70vh; /* 需要至少一个高度约束 */
  }

  /* 新增表格样式 */
  :deep(.el-table) {
    --el-table-border-color: #ebeef5;
    --el-table-header-bg-color: #f5f7fa;
  }

  :deep(.el-table th) {
    font-weight: 600;
  }

  :deep(.el-table td) {
    vertical-align: top;
  }

  .filter-container {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }
  </style>